package com.iris.live.services.services.impl;

import com.iris.live.services.common.StringUtils;
import com.iris.live.services.data.models.Lsh经销商表Model;
import com.iris.live.services.data.models.用户Model;
import com.iris.live.services.data.repositories.*;
import com.iris.live.services.interceptors.SessionInterceptor;
import com.iris.live.services.models.PageData;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.services.CarService;
import com.iris.live.services.services.IItemTranslationService;
import com.iris.live.services.services.ImgtService;
import com.iris.live.services.services.SetService;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional//(readOnly = true)
public class ImgtServiceImpl implements ImgtService {
    private static final Logger logger = LoggerFactory.getLogger(ImgtServiceImpl.class);
    @Autowired
    private ImgtRepository repository;
    @Autowired
    private Itask基础设置Repository itaskRepository;
    @Autowired
    private Lsh经销商表Repository lsh经销商表Repository;

    @Autowired
    private BIExtractRepository biExtractRepository;

    private CarService carService;

    @Autowired
    private IItemTranslationService itemTranslationService;

    @Autowired
    private 用户Repository 用户Repository;
    @Resource(name="setServiceImpl")
    private SetService setService;

    @Override
    public ResultData getStoreKPISecondPage(KPIPage items) {
        items.brand = getMultilanguage(items.brand);
        items.actualValueCode = getOrgCode(items.actualRole, items.actualValueCode);
        items.areaCode = getOrgCode(items.areaRole, items.areaCode);

        List<String> list = getStartAndEndDate(items.timeStatus, items.startDate);
        ResultData resultData = this.repository.getStoreKPISecondPage(list, items);

        List<Map> datas = resultData.getPageData().getData();
        if(! isChineseLanguage() && ("1".equals(items.modelType)) ) {
            if (datas != null && !datas.isEmpty()) {
                Map<String, String> translations = new HashMap<>();
                for (Map data : datas) {
                    translations.put(data.get("firstColumnRole").toString(), "");
                }
                itemTranslationService.translateToEnglish("车型级别", translations);
                for (Map data : datas) {
                    data.put("firstColumnRole", translations.get(data.get("firstColumnRole")));
                }
            }
        }

        return resultData;
    }

    @Override
    public ResultData getSaleKPISecondPage(KPIPage items) {
        items.brand = getMultilanguage(items.brand);
        items.actualValueCode = getOrgCode(items.actualRole, items.actualValueCode);
        items.areaCode = getOrgCode(items.areaRole, items.areaCode);

        List<String> list = getStartAndEndDate(items.timeStatus, items.startDate);
        ResultData resultData = this.repository.getSalesAndGpKPISecondPage(list, items);

        List<Map> datas = resultData.getPageData().getData();
        if(! isChineseLanguage() && ("1".equals(items.modelType)) ) {
            if (datas != null && !datas.isEmpty()) {
                Map<String, String> translations = new HashMap<>();
                for (Map data : datas) {
                    translations.put(data.get("firstColumnRole").toString(), "");
                }
                itemTranslationService.translateToEnglish("车型级别", translations);
                for (Map data : datas) {
                    data.put("firstColumnRole", translations.get(data.get("firstColumnRole")));
                }
            }
        }

        return resultData;
    }

    @Override
    public ResultData getGPKPISecondPage(KPIPage items) {
        items.brand = getMultilanguage(items.brand);
        items.actualValueCode = getOrgCode(items.actualRole, items.actualValueCode);
        items.areaCode = getOrgCode(items.areaRole, items.areaCode);

        List<String> list = getStartAndEndDate(items.timeStatus, items.startDate);

        ResultData resultData = this.repository.getSalesAndGpKPISecondPage(list, items);
        List<Map> datas = resultData.getPageData().getData();
        if(! isChineseLanguage() && ("1".equals(items.modelType)) ) {
            if (datas != null && !datas.isEmpty()) {
                Map<String, String> translations = new HashMap<>();
                for (Map data : datas) {
                    translations.put(data.get("firstColumnRole").toString(), "");
                }
                itemTranslationService.translateToEnglish("车型级别", translations);
                for (Map data : datas) {
                    data.put("firstColumnRole", translations.get(data.get("firstColumnRole")));
                }
            }
        }

        return resultData;
    }

    @Override
    public Map KPI(String name, String timeStatus, String currentDate, String role,
                   String roleCode, String areaRole, String areaCode, String brand, String actualValue,
                   String actualValueCode) {
        try {
            brand = this.getMultilanguage(brand);
            areaCode = getOrgCode(areaRole, areaCode);
            actualValueCode = getOrgCode(actualValue, actualValueCode);

            List<String> list = getStartAndEndDate(timeStatus, currentDate);
            return this.repository.KPI(name, list.get(0), list.get(1),
                    role, roleCode, areaRole, areaCode, brand, actualValue,
                    actualValueCode);
        }catch(Exception exc){
            throw exc;
        }
    }

    @Override
    public Map KPIs(String name, String timeStatus, String currentDate, String role, String roleCode, String areaRole, String areaCode, String brand) {
        brand = this.getMultilanguage(brand);

        // 获取统计开始时间，结束时间
        List<String> dataList = getStartAndEndDate(timeStatus, currentDate);
        List dealerList = this.repository.getStoreKpiDataWhenDealer(name, dataList, brand, roleCode);
        if (dealerList == null) {
            return null;
        } else {
            Map<String, List> reMap = new HashMap<>();
            reMap.put("Data", dealerList);
            return reMap;
        }
    }

    @Override
    public List KPI2(String name, String timeStatus, String currentDate, String role, String roleCode, String areaRole, String areaCode, String brand) {
        brand = this.getMultilanguage(brand);
        areaCode = getOrgCode(areaRole, areaCode);

        List<String> list = getStartAndEndDate(timeStatus, currentDate);
        List dealerList = this.repository.getSalesAndGpKpiWhenDealer(name, list.get(0), list.get(1), role, roleCode, areaRole, areaCode, brand);
        if (dealerList == null) {
            return null;
        } else {
            return dealerList;
        }
    }

    private String getOrgCode(String role, String value){
        if(StringUtils.isNullOrBlank(value)) {
            return value;
        }

        List resultSet = null;
        if(role.equalsIgnoreCase("大区")){

            resultSet = lsh经销商表Repository.getBigAreaCode(value);
        }if(role.equalsIgnoreCase("小区")){
            resultSet = lsh经销商表Repository.getSmallAreaCode(value);
        }if(role.equalsIgnoreCase("cta")){
            resultSet = lsh经销商表Repository.getCTACode(value);
        }
        if(resultSet == null || resultSet.isEmpty()){
            return value;
        }else{
            return resultSet.get(0).toString();
        }
    }

    @Override
    public List getAreaForDealer(String permit) {
        List resultList=new ArrayList();
        resultList=this.repository.getAreaForDealer(permit);
        if(resultList==null||resultList.size()==0){
            resultList=  this.repository.getAreaForDealerTwo(permit);
            if(resultList==null||resultList.size()==0){
                resultList=this.repository.getAreaForDealerThree(permit);
            }
        }
        return resultList;
    }

    @Override
    public List getPermitWithSameLshCoder(@RequestParam String permit) {
        return this.repository.getPermitWithSameLshCoder(permit);
    }

    @Override
    public List getApprovalUserInfo(String lshPermit, String type) {
        return this.repository.getApprovalUserInfo(lshPermit, type);
    }

    @Override
    public ResultData getApprovalUserInfoBrand(String permit, String type) {
        return this.repository.getApprovalUserInfoBrand(permit, type);
    }

    @Override
    public ResultData getApprovalUserInfoContract(ImgtService.getApprovalUserInfoContractBody rb, Integer type) {
        ResultData resultData = new ResultData();
        // 取得所有合同审批流数据，许可，人，级别
        List baseList = repository.getContractFlowSetting(type);

        if (baseList.size() == 0) {
            resultData.setResult("true");
            resultData.setMessage("未导入任何合同审批数据");
            return resultData;
        }

        // 先构建返回的List，用baseList会影响遍历
        List<Map<String, Object>> reList = new ArrayList<>();
        for (Object o : baseList) {
            Map baseMap = (Map) o;
            Map<String, Object> map = new HashMap<>();
            map.put("id", baseMap.get("id"));
            map.put("permit", baseMap.get("permit"));
            map.put("userOrPosition", baseMap.get("userOrPosition"));
            map.put("step", baseMap.get("step"));
            map.put("approvalLevel", baseMap.get("审批级别"));
            reList.add(map);
        }

//        // 添加itask的字段
//        List<Itask基础设置ModelPK> iPkList = new ArrayList<>(300);
//        for (Object o : baseList) {
//            Map map = (Map) o;
//            Itask基础设置ModelPK iPk = new Itask基础设置ModelPK();
//            iPk.set许可((String) map.get("permit"));
//            iPk.set设置项目((String) map.get("step"));
//            iPkList.add(iPk);
//        }
//        List<Itask基础设置Model> iList = itaskRepository.findAll(iPkList);
//
//        for (Itask基础设置Model iModel : iList) {
//            String iPermit = iModel.get许可();
//            String iStep = iModel.get设置项目();
//            String iValue = iModel.get值();
//            for (int i = 0; i < baseList.size(); i++) {
//                Object o = baseList.get(i);
//                String basePermit = (String) ((Map) o).get("permit");
//                String baseStep = (String) ((Map) o).get(ApprovalUtils.STEP);
//                if (iPermit.equals(basePermit) && iStep.equals(baseStep)) {
//                    reList.get(i).put("key", baseStep);
//                    reList.get(i).put("value", iValue);
//                }
//            }
//        }

        // 添加经销商字段
        List<String> permitList = new ArrayList<>(100);
        for (Object o : baseList) {
            permitList.add((String) ((Map) o).get("permit"));
        }
        List<Lsh经销商表Model> dealerList = lsh经销商表Repository.findAll(permitList);

        for (Lsh经销商表Model dealerModel : dealerList) {
            String dPermit = dealerModel.getBmbs();
            String dealerName = dealerModel.get经销商名();
            String bigArea = dealerModel.get大区();
            for (int i = 0; i < baseList.size(); i++) {
                Object o = baseList.get(i);
                String basePermit = (String) ((Map) o).get("permit");
                if (dPermit.equals(basePermit)) {
                    reList.get(i).put("dealerName", dealerName);
                    reList.get(i).put("bigArea", bigArea);
                }
            }
        }
        // 添加用户字段
        List<String> userNameList = new ArrayList<>(100);
        for (int i = 0; i < baseList.size(); i++) {
            String userOrPosition = (String) ((Map) baseList.get(i)).get("userOrPosition");
            if (!setService.isRoleName(userOrPosition)) {// 如果存的是组织
                reList.get(i).put("department", userOrPosition.split("_")[0]);
                reList.get(i).put("position", userOrPosition.split("_")[1]);
                reList.get(i).put("userName", "");
                reList.get(i).put("userOrPosition", ""); // 更新原字段
                reList.get(i).put("userCell", "");
            } else { //如果存的是用户
                userNameList.add(userOrPosition);
            }
        }
        List<用户Model> userList = 用户Repository.findAll(userNameList);
        for (用户Model model : userList) {
            String userEmail = model.get用户名();
            String userName = model.get人员姓名();
            String userCell = model.get人员电话();
            String position = model.get角色();
            String department = model.get所属部门();
            for (int i = 0; i < baseList.size(); i++) {
                Object o = baseList.get(i);
                String baseUserEmail = (String) ((Map) o).get("userOrPosition");
                if (userEmail.equalsIgnoreCase(baseUserEmail)) { // 用户表与审批设置表，存在大小写不同的问题
                    reList.get(i).put("department", department);
                    reList.get(i).put("position", position);
                    reList.get(i).put("userName", userName);
                    reList.get(i).put("userCell", userCell);
                }
            }
        }

        // 按条件过滤数据
        for (int i = 0; i < reList.size(); i++) {
            Map m = reList.get(i);
            if (rb.permit != null && rb.permit.length() != 0 && !((String) m.get("permit")).toLowerCase().contains(rb.permit.toLowerCase())) {
                reList.set(i, null);
            }
            if (rb.dlName != null && rb.dlName.length() != 0 && !((String) m.get("dealerName")).toLowerCase().contains(rb.dlName.toLowerCase())) {
                reList.set(i, null);
            }
            if (rb.role != null && rb.role.length() != 0 && !((String) m.get("position")).toLowerCase().contains(rb.role.toLowerCase())) {
                reList.set(i, null);
            }
            if (rb.bigArea != null && rb.bigArea.length() != 0 && !((String) m.get("bigArea")).toLowerCase().contains(rb.bigArea.toLowerCase())) {
                reList.set(i, null);
            }
        }

        // 过滤list中的null
        List<Map> noNullReList = new ArrayList<>();
        for (Map map : reList) {
            if (map != null) {
                noNullReList.add(map);
            }
        }

        // 分页
        int s = rb.getPageSize();
        int i = rb.getPageIndex();
        int maxIndex = noNullReList.size() - 1;
        if (s == 0 && i == 0) { // 这种情况下要求返回所有数据

        } else {
            if (s * (i + 1) <= maxIndex) { // 结束索引在内
                noNullReList = noNullReList.subList(s * i, s * (i + 1));
            } else if (s * i <= maxIndex) { // 结束索引超出，但起始索引在内
                noNullReList = noNullReList.subList(s * i, maxIndex + 1);
            } else { // 索引都在外
                noNullReList = null;
            }
        }

        resultData.setResult("true");
        resultData.setMessage("正常");
        resultData.setPageData(new PageData(noNullReList, maxIndex + 1));
        return resultData;
    }

    @Override
    public List getDepartmentByShowRoom(String permit) {
        return this.repository.getDepartmentByShowRoom(permit);
    }

    @Override
    public List getUserNameByPosition(String permit, String department, String role) {
        return this.repository.getUserNameByPosition(permit, department, role);
    }

    @Override
    public List getPositionByDepartment(String permit, String department) {
        return this.repository.getPositionByDepartment(permit, department);
    }

    /**
     * 根据传入时间与类型，确定统计数据的开始时间，结束时间
     * 20170426新需求，统计的结束时间，就是界面上选择的时间，如果要统计过去某月，需要在界面上选择该月最后一天
     *
     * @param timeStatus 界面选择的时间类型，直接传到后台，枚举值{DTD MTD QTD YTD}
     * @param chosenDate 界面选择的时间，直接传到后台
     * @return 两个元素的LIST，开始日期，结束日期
     */
    private List<String> getStartAndEndDate(String timeStatus, String chosenDate) {
        List<String> list = new ArrayList<>(2);
        String year = chosenDate.substring(0, 4);
        String month = chosenDate.substring(5, 7);
        if ("DTD".equals(timeStatus)) { // 天
            list.add(chosenDate);
        } else if ("MTD".equals(timeStatus)) { // 月
            list.add(year + "-" + month + "-01");
        } else if ("QTD".equals(timeStatus)) { // 季
            Integer int_month = Integer.parseInt(month);
            // 根据月份得到季度第一天
            if (1 <= int_month && int_month < 4) {
                list.add(year + "-01-01");
            } else if (4 <= int_month && int_month < 7) {
                list.add(year + "-04-01");
            } else if (7 <= int_month && int_month < 10) {
                list.add(year + "-07-01");
            } else {
                list.add(year + "-10-01");
            }
        } else if ("YTD".equals(timeStatus)) { // 年
            list.add(year + "-01-01");
        } else { // 不允许出现的情况
            list.add("1970-01-01");
            logger.error("getStartAndEndDate非法的参数, timeStatus = ", timeStatus);
        }
        list.add(chosenDate);  // 结束日期是当天
        return list;
    }

    private boolean isChineseLanguage(){
        return "CN".equalsIgnoreCase(ThreadContext.get("LIVE_LANGUAGE"));
    }

    private String getMultilanguage(String name){
        if(! isChineseLanguage()){
            return itemTranslationService.translateToEnglish("车型级别", name);
        }

        return name;
    }
}
